<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>仿微信桌面聊天界面</title>
    <link rel="stylesheet" href="/css/all.min.css"/>
    <link rel="stylesheet" href="/css/wechat-chat.css">
</head>
<body>
    <div class="container">
        <!-- 功能区 -->
        <div class="sidebar">
			<div class="sidebar-item ">
                <img th:src="(${#strings.isEmpty(user.avatar)}) ? @{/img/profile.jpg} : @{${user.avatar}}" th:onerror="this.src='img/profile.jpg'" class="img-circle" alt="User Image">
			</div>
			<div class="sidebar-item active" data-tab="chat"><i class="fa-solid fa-comment"></i></div>
            <div class="sidebar-item" data-tab="users"><i class="fa-solid fa-user-group"></i></div>
            <div class="sidebar-item" data-tab="files"><i class="fa-solid fa-folder"></i></div>
            <div class="sidebar-item" data-tab="settings"><i class="fa-solid fa-gear"></i></div>
        </div>
        
        <!-- 会话列表 -->
        <div class="chat-list">
            <!-- 聊天列表 -->
            <div class="tab-content chat-tab active" id="chat-tab">
                <div class="chat-list-header">
                    <div class="search-box">
                        <i class="fa-solid fa-magnifying-glass" style="color: #999; margin-right: 5px;"></i>
                        <input type="text" placeholder="搜索" id="search-input">
                        <div class="search-results" id="search-results" style="display: none;">
                            <div class="search-results-header">
                                <span>搜索结果</span>
                                <button onclick="closeSearchResults()">×</button>
                            </div>
                            <div class="search-results-content" id="search-results-content">
                                <!-- 搜索结果会动态填充到这里 -->
                            </div>
                        </div>
                    </div>
                </div>
                <div class="chat-list-content" id="chat-list-content">
                </div>
            </div>
            
            <!-- 用户列表 -->
            <div class="tab-content user-tab" id="users-tab" style="display: none;">
                <div class="user-list-header">
                    <div class="search-box">
                        <i class="fa-solid fa-magnifying-glass" style="color: #999; margin-right: 5px;"></i>
                        <input type="text" placeholder="搜索用户" id="user-search-input">
                    </div>
                </div>
                <div class="user-list-content" id="user-list-content">
                    <!-- 用户列表会动态填充到这里 -->
                    <div class="chat-item" th:attr="data-chat=${user.userId}" th:each="user : ${userList}">
                        <div class="avatar">[[${#strings.substring(user.userName, 0, 1)}]]</div>
                        <div class="chat-info">
                            <div class="chat-name">[[${user.userName}]]</div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 文件列表 -->
            <div class="tab-content file-tab" id="file-tab" style="display: none;">
                <div class="file-list-content">
                    <div class="no-content">
                        <i class="fa-solid fa-folder" style="font-size: 48px; color: #ccc; margin-bottom: 16px;"></i>
                        <p>文件管理功能待实现</p>
                    </div>
                </div>
            </div>
            
            <!-- 设置页面 -->
            <div class="tab-content settings-tab" id="settings-tab" style="display: none;">
                <div class="settings-content">
                    <div class="no-content">
                        <i class="fa-solid fa-gear" style="font-size: 48px; color: #ccc; margin-bottom: 16px;"></i>
                        <p>设置功能待实现</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 聊天区 -->
        <div class="chat-area" id="chat-area" style="display: none;">
            <div class="chat-header">
                <div class="chat-title" id="chat-title">UserName</div>
                <div class="chat-actions" style="display:none;">
                    <i class="fa-solid fa-phone action-btn"></i>
                    <i class="fa-solid fa-video action-btn"></i>
                    <i class="fa-solid fa-ellipsis-h action-btn"></i>
                </div>
            </div>
            <div class="chat-messages" id="chat-messages">
				<!--消息对话-->
            </div>
            <div class="chat-input">
                <div class="input-tools">
                    <i class="fa-regular fa-face-smile tool-btn"></i>
                    <i class="fa-solid fa-paperclip tool-btn"></i>
                    <i class="fa-solid fa-image tool-btn"></i>
                    <i class="fa-solid fa-folder-open tool-btn"></i>
                </div>
                <div class="input-box">
                    <textarea placeholder="输入消息..." id="message-input"></textarea>
                    <button class="send-btn" id="send-btn">发送</button>
                </div>
            </div>
        </div>
        
        <!-- 默认显示区域 - 当没有选择聊天时显示 -->
        <div class="default-area" id="default-area">
            <div class="welcome-message">
                <i class="fa-solid fa-comments" style="font-size: 96px; color: #ddd;"></i>
            </div>
        </div>
    </div>

	<th:block th:insert="~{include :: footer}" />
    <script src="/js/sockjs/sockjs.min.js"></script>
    <script src="/js/sockjs/stomp.min.js"></script>
    <script th:inline="javascript">
        // 获取DOM元素
        const messageInput = document.getElementById('message-input');
        const sendBtn = document.getElementById('send-btn');
        const chatMessages = document.querySelector('.chat-messages');
        const chatItems = document.querySelectorAll('.chat-item');
        const chatTitle = document.querySelector('.chat-title');
        const chatActions = document.querySelector('.chat-actions');
        const toolBtns = document.querySelectorAll('.tool-btn');
        const searchInput = document.getElementById('search-input');
        const searchResults = document.getElementById('search-results');
        const sidebarItems = document.querySelectorAll('.sidebar-item[data-tab]');
        const tabContents = document.querySelectorAll('.tab-content');
        const userSearchInput = document.getElementById('user-search-input');
        const userListContent = document.getElementById('user-list-content');

        const chatArea = document.getElementById('chat-area');
        const defaultArea = document.getElementById('default-area');
        
        // WebSocket相关变量
        let stompClient = null;
        let currentChatUser = null;
        let currentSessionId = null;
        
        // 文件上传相关变量
        let fileInput = null;
        let imageInput = null;
        
        // 聊天状态相关变量
        let isTyping = false;
        let typingTimer = null;
        let currentPage = 1;
        const MESSAGES_PER_PAGE = 20;
        
        // 初始化WebSocket连接
        function connectWebSocket() {
            try {
                console.log('开始建立WebSocket连接...');
                const socket = new SockJS('/ws');
                stompClient = Stomp.over(socket);
                
                // 设置调试模式
                // stompClient.debug = function(str) {
                //     console.log('STOMP: ' + str);
                // };
                
                stompClient.connect({}, function(frame) {
                    console.log('WebSocket连接成功! Connected: ' + frame);
                    console.log('会话ID: ' + frame.headers['user-name']);
                    console.log('开始订阅消息队列...');
                    
                    // 订阅私聊消息队列
                    stompClient.subscribe('/user/queue/private', function(message) {
                        console.log('=== 前端接收消息日志开始 ===');
                        console.log('当前用户ID: [[${user.userId}]]');
                        console.log('完整消息对象:', message);
                        try {
                            const receivedMessage = JSON.parse(message.body);
                            
                            // 修复消息显示格式
                            receivedMessage.sender = receivedMessage.fromUser || '未知用户';
                            receivedMessage.from = receivedMessage.fromUser || '未知用户';
                            console.log('📤 准备显示消息...');
                            displayMessage(receivedMessage, 'received');
                            console.log('✅ 消息显示完成');
                        } catch (error) {
                            console.error('❌ 消息解析错误:', error);
                            
                            // 尝试直接显示原始消息
                            const errorMessage = {
                                content: message.body || '无法解析的消息',
                                from: '系统',
                                timestamp: new Date().getTime(),
                                messageType: 1
                            };
                            displayMessage(errorMessage, 'received');
                        }
                        
                        console.log('=== 前端接收消息日志结束 ===');
                    });
                    
                    console.log('已订阅 /user/queue/private 频道');
                    
                    // 订阅消息已读通知
                    stompClient.subscribe('/user/queue/read', function(message) {
                        console.log('接收到消息已读通知:', message.body);
                        const messageId = JSON.parse(message.body);
                        markMessageAsRead(messageId);
                    });
                    
                    // 订阅消息撤回通知
                    stompClient.subscribe('/user/queue/recall', function(message) {
                        console.log('接收到消息撤回通知:', message.body);
                        const messageId = JSON.parse(message.body);
                        recallMessage(messageId);
                    });
                    
                    // 订阅未读消息数
                    stompClient.subscribe('/user/queue/unread.count', function(message) {
                        console.log('接收到未读消息数:', message.body);
                        const unreadCount = JSON.parse(message.body);
                        updateUnreadCount(unreadCount);
                    });
                    
                    // 通知服务器用户上线
                    if (stompClient.connected) {
                        stompClient.send('/app/chat.online', {}, 'online');
                        console.log('已发送上线通知');
                    }
                    
                    console.log('所有订阅完成，WebSocket连接已就绪');
                    
                }, function(error) {
                    console.error('WebSocket连接失败: ', error);
                    console.log('将在5秒后尝试重连...');
                    setTimeout(connectWebSocket, 5000); // 5秒后重连
                });
            } catch (error) {
                console.error('WebSocket连接异常:', error);
                console.log('将在5秒后尝试重连...');
                setTimeout(connectWebSocket, 5000);
            }
        }
        
        // 初始化文件上传功能
        function initializeFileUpload() {
            // 创建隐藏的文件输入框
            fileInput = document.createElement('input');
            fileInput.type = 'file';
            fileInput.style.display = 'none';
            fileInput.accept = '*/*';
            
            imageInput = document.createElement('input');
            imageInput.type = 'file';
            imageInput.style.display = 'none';
            imageInput.accept = 'image/*';
            
            document.body.appendChild(fileInput);
            document.body.appendChild(imageInput);
            
            // 绑定文件上传事件
            fileInput.addEventListener('change', handleFileUpload);
            imageInput.addEventListener('change', handleImageUpload);
        }
        
        // 处理文件上传
        function handleFileUpload(event) {
            const file = event.target.files[0];
            if (!file || !currentChatUser) return;
            
            const formData = new FormData();
            formData.append('file', file);
            formData.append('to', currentChatUser);
            
            fetch('/api/upload/file', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    console.log('文件上传成功:', data);
                    // 文件消息会通过WebSocket自动显示
                } else {
                    alert('文件上传失败: ' + data.error);
                }
            })
            .catch(error => {
                console.error('文件上传错误:', error);
                alert('文件上传失败');
            })
            .finally(() => {
                fileInput.value = '';
            });
        }
        
        // 处理图片上传
        function handleImageUpload(event) {
            const image = event.target.files[0];
            if (!image || !currentChatUser) return;
            
            const formData = new FormData();
            formData.append('image', image);
            formData.append('to', currentChatUser);
            
            fetch('/api/upload/image', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    console.log('图片上传成功:', data);
                    // 图片消息会通过WebSocket自动显示
                } else {
                    alert('图片上传失败: ' + data.error);
                }
            })
            .catch(error => {
                console.error('图片上传错误:', error);
                alert('图片上传失败');
            })
            .finally(() => {
                imageInput.value = '';
            });
        }
        
        // 显示消息
        function displayMessage(message, type) {
            const messageElement = document.createElement('div');
            messageElement.className = `message ${type}`;
            messageElement.setAttribute('data-message-id', message.id || new Date().getTime());
            
            // 使用消息中的时间戳，如果没有则使用当前时间
            const timestamp = message.timestamp || new Date().getTime();
            const messageTime = new Date(timestamp);
            const timeString = `${messageTime.getHours()}:${messageTime.getMinutes().toString().padStart(2, '0')}`;
            
            let messageContent = '';
            
            // 根据消息类型显示不同内容
            switch (message.messageType) {
                case 1: // 文本消息
                    messageContent = `<div class="message-bubble">${message.content}</div>`;
                    break;
                case 2: // 图片消息
                    messageContent = `
                        <div class="message-bubble image-message">
                            <img src="${message.fileUrl}" alt="图片" onclick="openImagePreview('${message.fileUrl}')" style="max-width: 200px; max-height: 200px; cursor: pointer;">
                            <div class="image-caption">${message.fileName || '图片'}</div>
                        </div>
                    `;
                    break;
                case 3: // 文件消息
                    messageContent = `
                        <div class="message-bubble file-message">
                            <div class="file-icon">📎</div>
                            <div class="file-info">
                                <div class="file-name">${message.fileName || '文件'}</div>
                                <div class="file-size">${formatFileSize(message.fileSize)}</div>
                            </div>
                            <a href="${message.fileUrl}" download="${message.fileName}" class="download-btn">下载</a>
                        </div>
                    `;
                    break;
                default:
                    messageContent = `<div class="message-bubble">${message.content}</div>`;
            }
            
            if (type === 'received') {
                // 接收的消息显示头像和发送者信息
                const senderInitial = message.from ? message.from.charAt(0).toUpperCase() : '?';
                messageElement.innerHTML = `
                    <div class="avatar">${senderInitial}</div>
                    <div class="message-content">
                        ${messageContent}
                        <div class="message-time">${timeString}</div>
                    </div>
                `;
            } else {
                // 发送的消息只显示内容和时间
                messageElement.innerHTML = `
                    <div class="message-content">
                        ${messageContent}
                        <div class="message-time">${timeString}</div>
                    </div>
                `;
            }
            
            chatMessages.appendChild(messageElement);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (!bytes) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        
        // 图片预览功能
        function openImagePreview(imageUrl) {
            const modal = document.createElement('div');
            modal.id = 'image-preview-modal';
            modal.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0,0,0,0.9);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 1000;
            `;
            
            modal.innerHTML = `
                <div class="image-preview-container" style="position: relative; max-width: 90%; max-height: 90%;">
                    <img src="${imageUrl}" style="max-width: 100%; max-height: 100%; object-fit: contain;" 
                         onclick="event.stopPropagation()" class="preview-image">
                    <div class="image-preview-actions" style="position: absolute; top: 20px; right: 20px; display: flex; gap: 10px;">
                        <button onclick="closeImagePreview()" style="background: none; border: none; color: white; font-size: 24px; cursor: pointer; padding: 5px;">×</button>
                        <a href="${imageUrl}" download style="background: rgba(255,255,255,0.2); border: none; color: white; padding: 8px 12px; border-radius: 4px; cursor: pointer; text-decoration: none;">下载</a>
                    </div>
                </div>
            `;
            
            // 添加键盘事件监听
            const keyHandler = function(e) {
                if (e.key === 'Escape') {
                    closeImagePreview();
                }
            };
            
            document.addEventListener('keydown', keyHandler);
            
            modal.addEventListener('click', function() {
                closeImagePreview();
            });
            
            document.body.appendChild(modal);
            
            // 存储事件监听器，以便后续移除
            modal._keyHandler = keyHandler;
        }
        
        // 关闭图片预览
        function closeImagePreview() {
            const modal = document.getElementById('image-preview-modal');
            if (modal) {
                if (modal._keyHandler) {
                    document.removeEventListener('keydown', modal._keyHandler);
                }
                modal.remove();
            }
        }
        
        // 发送消息
        function sendMessage() {
            const content = messageInput.value.trim();
            console.log('发送消息按钮被点击，内容:', content);
            console.log('当前聊天用户:', currentChatUser);
            console.log('WebSocket连接状态:', stompClient ? stompClient.connected : '未连接');
            
            if (content && stompClient && stompClient.connected && currentChatUser) {
                const message = {
                    to: currentChatUser,
                    content: content,
                    messageType: 1 // 文本消息
                };
                
                console.log('准备发送消息:', message);
                console.log('目标路径: /app/chat.send');
                
                stompClient.send('/app/chat.send', {}, JSON.stringify(message));
                
                console.log('消息已发送到后端');
                
                // 本地显示已发送消息
                const messageElement = document.createElement('div');
                messageElement.className = 'message sent';
                
                const now = new Date();
                const timeString = `${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`;
                
                messageElement.innerHTML = `
                    <div class="message-content">
                        <div class="message-bubble">${content}</div>
                        <div class="message-time">${timeString}</div>
                    </div>
                `;
                
                chatMessages.appendChild(messageElement);
                messageInput.value = '';
                chatMessages.scrollTop = chatMessages.scrollHeight;
            }
        }
        
        // 标记消息已读
        function markMessageAsRead(messageId) {
            const messageElement = document.querySelector(`[data-message-id="${messageId}"]`);
            if (messageElement) {
                messageElement.classList.add('read');
            }
        }
        
        // 撤回消息
        function recallMessage(messageId) {
            const messageElement = document.querySelector(`[data-message-id="${messageId}"]`);
            if (messageElement) {
                const bubble = messageElement.querySelector('.message-bubble');
                bubble.innerHTML = '<span style="color: #999; font-style: italic;">消息已被撤回</span>';
                messageElement.classList.add('recalled');
            }
        }
        
        // 更新未读消息数
        function updateUnreadCount(count) {
            const chatItem = document.querySelector(`[data-chat="${currentChatUser}"]`);
            if (chatItem) {
                let badge = chatItem.querySelector('.unread-badge');
                if (!badge) {
                    badge = document.createElement('div');
                    badge.className = 'unread-badge';
                    chatItem.appendChild(badge);
                }
                badge.textContent = count > 99 ? '99+' : count;
                badge.style.display = count > 0 ? 'block' : 'none';
            }
        }
        
        // 处理输入状态
        function handleTyping() {
            if (stompClient && stompClient.connected && currentChatUser) {
                const typingData = {
                    to: currentChatUser,
                    typing: true
                };
                stompClient.send('/app/chat.typing', {}, JSON.stringify(typingData));
                
                // 3秒后发送停止输入状态
                setTimeout(() => {
                    if (stompClient && stompClient.connected) {
                        const stopTypingData = {
                            to: currentChatUser,
                            typing: false
                        };
                        stompClient.send('/app/chat.typing', {}, JSON.stringify(stopTypingData));
                    }
                }, 3000);
            }
        }
        
        // 切换聊天会话
        chatItems.forEach(item => {
            item.addEventListener('click', function() {
                // 移除所有活跃状态
                chatItems.forEach(i => i.classList.remove('active'));
                // 添加当前活跃状态
                this.classList.add('active');
                
                // 更新当前聊天用户
                currentChatUser = this.getAttribute('data-chat');
                chatTitle.textContent = this.querySelector('.chat-name').textContent;
                
                // 显示聊天操作按钮
                chatActions.style.display = 'flex';
                
                // 清空当前聊天记录
                chatMessages.innerHTML = '';
                
                // 获取历史消息（这里需要调用后端API）
                fetchHistoryMessages(currentChatUser);
                
                // 获取未读消息数
                if (stompClient && stompClient.connected) {
                    stompClient.send('/chat.unread.count', {}, currentChatUser);
                }
            });
        });
        
        // 获取历史消息（模拟）
        function fetchHistoryMessages(userId) {
            // 这里需要调用后端API获取历史消息
            // 暂时使用模拟数据
            const messages = [
                { id: 1, from: userId, content: '你好！最近怎么样？', timestamp: '14:20', type: 'received' },
                { id: 2, from: 'me', content: '我很好，谢谢关心！', timestamp: '14:21', type: 'sent' },
                { id: 3, from: userId, content: '周末有空一起喝咖啡吗？', timestamp: '14:22', type: 'received' }
            ];
            
            messages.forEach(msg => {
                displayMessage(msg, msg.type);
            });
        }
        
        // 发送按钮点击事件
        sendBtn.addEventListener('click', sendMessage);
        
        // 回车发送消息
        messageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
        
        // 输入框输入事件（输入状态）
        messageInput.addEventListener('input', function() {
            handleTyping();
        });
        
        // 绑定工具按钮事件
        toolBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                const iconClass = this.className;
                if (iconClass.includes('fa-paperclip')) {
                    fileInput.click();
                } else if (iconClass.includes('fa-image')) {
                    imageInput.click();
                } else if (iconClass.includes('fa-face-smile')) {
                    // 表情功能
                    alert('表情功能待实现');
                } else if (iconClass.includes('fa-folder-open')) {
                    // 文件管理
                    alert('文件管理功能待实现');
                }
            });
        });
        
        // 侧边栏选项切换功能
        sidebarItems.forEach(item => {
            item.addEventListener('click', function() {
                const tabName = this.getAttribute('data-tab');
                
                // 移除所有活跃状态
                sidebarItems.forEach(i => i.classList.remove('active'));
                tabContents.forEach(tab => {
                    tab.classList.remove('active');
                    tab.style.display = 'none';
                });
                
                // 添加当前活跃状态
                this.classList.add('active');
                
                // 显示对应的内容
                const targetTab = document.getElementById(tabName + '-tab');
                if (targetTab) {
                    targetTab.style.display = 'block';
                    targetTab.classList.add('active');
                }
                
                // 如果是用户列表，加载用户数据
                if (tabName === 'users') {
                    loadUserList();
                }
            });
        });
        
        // 用户搜索功能
        let userSearchTimeout = null;
        userSearchInput.addEventListener('input', function() {
            const keyword = this.value.trim();
            
            // 防抖处理
            clearTimeout(userSearchTimeout);
            userSearchTimeout = setTimeout(() => {
                if (keyword.length > 0) {
                    searchUsers(keyword);
                } else {
                    loadUserList();
                }
            }, 500);
        });
        
        // 加载用户列表
        function loadUserList() {
            fetch('/api/search/messages?keyword=', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displayUserList(data.filteredUsers || []);
                } else {
                    console.error('获取用户列表失败:', data.error);
                    displayUserList([]);
                }
            })
            .catch(error => {
                console.error('获取用户列表请求错误:', error);
                displayUserList([]);
            });
        }
        
        // 搜索用户
        function searchUsers(keyword) {
            fetch(`/api/search/messages?keyword=${encodeURIComponent(keyword)}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displayUserList(data.filteredUsers || []);
                } else {
                    console.error('搜索用户失败:', data.error);
                    displayUserList([]);
                }
            })
            .catch(error => {
                console.error('搜索用户请求错误:', error);
                displayUserList([]);
            });
        }
        
        // 显示用户列表
        function displayUserList(users) {
            if (!userListContent) return;
            
            if (users.length === 0) {
                userListContent.innerHTML = `
                    <div class="no-results">
                        <i class="fa-solid fa-user-group" style="font-size: 48px; color: #ccc; margin-bottom: 16px;"></i>
                        <p>暂无用户</p>
                    </div>
                `;
            } else {
                let html = '';
                users.forEach(user => {
                    html += `
                        <div class="user-item" data-user-id="${user.userId}" data-user-name="${user.userName}" onclick="startChatWithUser('${user.userId}', '${user.userName}')">
                            <div class="avatar">${user.userName ? user.userName.charAt(0).toUpperCase() : 'U'}</div>
                            <div class="user-info">
                                <div class="user-name">${user.userName || '未知用户'}</div>
                                <div class="user-status">${user.email || ''}</div>
                            </div>
                        </div>
                    `;
                });
                userListContent.innerHTML = html;
            }
        }
        
        // 开始与用户聊天
        function startChatWithUser(userId, userName) {
            // 切换到聊天列表
            const chatTab = document.querySelector('[data-tab="chat"]');
            if (chatTab) {
                chatTab.click();
            }
            
            // 检查是否已存在与用户的聊天
            const existingChat = document.querySelector(`[data-chat="${userId}"]`);
            if (existingChat) {
                existingChat.click();
            } else {
                // 创建新的聊天项
                const chatListContent = document.getElementById('chat-list-content');
                const newChatItem = document.createElement('div');
                newChatItem.className = 'chat-item';
                newChatItem.setAttribute('data-chat', userId);
                
                const now = new Date();
                const timeString = `${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`;
                
                newChatItem.innerHTML = `
                    <div class="avatar">${userName ? userName.charAt(0).toUpperCase() : 'U'}</div>
                    <div class="chat-info">
                        <div class="chat-name">${userName || '新用户'}</div>
                    </div>
                `;
                
                // 添加到列表顶部
                chatListContent.insertBefore(newChatItem, chatListContent.firstChild);
                
                // 绑定点击事件
                newChatItem.addEventListener('click', function() {
                    // 移除所有活跃状态
                    document.querySelectorAll('.chat-item').forEach(i => i.classList.remove('active'));
                    // 添加当前活跃状态
                    this.classList.add('active');
                    
                    // 更新当前聊天用户
                    currentChatUser = userId;
                    chatTitle.textContent = userName;
                    
                    // 显示聊天操作按钮
                    chatActions.style.display = 'flex';
                    
                    // 清空当前聊天记录
                    chatMessages.innerHTML = '';
                    
                    // 获取历史消息
                    fetchHistoryMessages(userId);
                });
                
                // 切换到新聊天
                newChatItem.click();
                chatArea.style.display = 'flex';
                defaultArea.style.display = 'none';
            }
        }
        
        // 搜索功能实现
        let searchTimeout = null;
        
        // 搜索输入事件监听
        searchInput.addEventListener('input', function() {
            const keyword = this.value.trim();
            
            // 防抖处理
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                if (keyword.length > 0) {
                    performSearch(keyword);
                } else {
                    closeSearchResults();
                }
            }, 500);
        });
        
        // 执行搜索
        function performSearch(keyword) {
            fetch(`/api/search/messages?keyword=${encodeURIComponent(keyword)}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displaySearchResults(data, keyword, data.stats);
                } else {
                    console.error('搜索失败:', data.error);
                    showSearchError('搜索失败: ' + data.error);
                }
            })
            .catch(error => {
                console.error('搜索请求错误:', error);
                showSearchError('网络错误，请重试');
            });
        }
        
        // 显示搜索结果
        function displaySearchResults(data, keyword, stats) {
            var messages = data.messages;
            var users = data.filteredUserList;
            const resultsContent = document.getElementById('search-results-content');
            
            if (messages.length === 0) {
                resultsContent.innerHTML = `
                    <div class="no-results">
                        <i class="fa-solid fa-search" style="font-size: 48px; color: #ccc; margin-bottom: 16px;"></i>
                        <p>没有找到与 "${keyword}" 相关的消息</p>
                    </div>
                `;
            } else {
                let html = `
                    <div class="search-stats">
                        <span>找到 ${stats.totalResults} 条相关消息</span>
                    </div>
                `;
                
                messages.forEach(message => {
                    html += createSearchResultItem(message, keyword);
                });
                
                resultsContent.innerHTML = html;
            }
            
            // 显示搜索结果面板
            searchResults.style.display = 'block';
            
            // 添加点击搜索结果跳转功能
            setTimeout(() => {
                const resultItems = resultsContent.querySelectorAll('.search-result-item');
                resultItems.forEach(item => {
                    item.addEventListener('click', function() {
                        const messageId = this.getAttribute('data-message-id');
                        const chatUser = this.getAttribute('data-chat-user');
                        navigateToMessage(messageId, chatUser);
                    });
                });
            }, 100);
        }
        
        // 创建搜索结果项
        function createSearchResultItem(message, keyword) {
            const time = new Date(message.timestamp).toLocaleTimeString('zh-CN', { 
                hour: '2-digit', 
                minute: '2-digit' 
            });
            
            // 高亮关键词
            const highlightedContent = message.content.replace(
                new RegExp(keyword, 'gi'), 
                match => `<span class="highlight">${match}</span>`
            );
            
            return `
                <div class="search-result-item" data-message-id="${message.id}" data-chat-user="${message.from}">
                    <div class="result-avatar">${message.from.charAt(0).toUpperCase()}</div>
                    <div class="result-content">
                        <div class="result-sender">${message.from}</div>
                        <div class="result-text">${highlightedContent}</div>
                        <div class="result-time">${time}</div>
                    </div>
                </div>
            `;
        }
        
        // 跳转到具体消息
        function navigateToMessage(messageId, chatUser) {
            // 切换到对应聊天
            const chatItem = document.querySelector(`[data-chat="${chatUser}"]`);
            if (chatItem) {
                chatItem.click();
                
                // 滚动到指定消息
                setTimeout(() => {
                    const messageElement = document.querySelector(`[data-message-id="${messageId}"]`);
                    if (messageElement) {
                        messageElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        messageElement.classList.add('highlighted');
                        setTimeout(() => {
                            messageElement.classList.remove('highlighted');
                        }, 2000);
                    }
                }, 500);
            }
            
            closeSearchResults();
        }
        
        // 关闭搜索结果
        function closeSearchResults() {
            searchResults.style.display = 'none';
            searchInput.value = '';
        }
        
        // 显示搜索错误
        function showSearchError(errorMessage) {
            const resultsContent = document.getElementById('search-results-content');
            resultsContent.innerHTML = `
                <div class="search-error">
                    <i class="fa-solid fa-exclamation-triangle" style="color: #f44336; font-size: 24px; margin-bottom: 8px;"></i>
                    <p>${errorMessage}</p>
                </div>
            `;
            searchResults.style.display = 'block';
        }
        
        // 页面加载完成后连接WebSocket
        window.addEventListener('load', function() {
            connectWebSocket();
            initializeFileUpload();
            
            // 默认选中第一个聊天
            if (chatItems.length > 0) {
                chatItems[0].click();
            }
        });
        
        // 页面卸载时断开连接
        window.addEventListener('beforeunload', function() {
            if (stompClient) {
                stompClient.send('/app/chat.online', {}, 'offline');
                stompClient.disconnect();
            }
        });
        
        // 初始化滚动条位置
        chatMessages.scrollTop = chatMessages.scrollHeight;
    </script>
</body>
</html>